package com.boomkeeper.archive.file;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boomkeeper.core.config.BaseConfig;
import com.google.common.io.Files;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

@Component("extract")
public class Extract {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Extract.class);
	
	@Autowired
	private BaseConfig baseConfig;
	
	public void unZipFiles() {
		this.unZipFiles(baseConfig.getLteVersion().getLteZipPath(), baseConfig.getLteVersion().getLteZipPath());
	}

	public void unZipFiles(String srcFile, String destPath) {
		File file = new File(srcFile);
		if (file.isDirectory()) {
			File[] listFiles = file.listFiles();
			for(File listFile : listFiles) {
				this.unZipFiles(listFile.getAbsolutePath(), destPath);
			}
		} else if(file.isFile() && "zip".equalsIgnoreCase(Files.getFileExtension(file.getName()))){
			try {
		         ZipFile zipFile = new ZipFile(srcFile);
		         zipFile.extractAll(destPath);
		    } catch (ZipException e) {
		    	LOGGER.error("解压文件{}发生异常", e);
		    }
		}
	}
	
	public void unZipFiles(String srcFile, String destPath, String password) {
	    try {
	         ZipFile zipFile = new ZipFile(srcFile);
	         if (zipFile.isEncrypted()) {
	            zipFile.setPassword(password);
	         }
	         zipFile.extractAll(destPath);
	    } catch (ZipException e) {
	    	LOGGER.error("解压文件{}发生异常", e);
	    }
	}
}